<?php
	defined( "AZ_EXE_" ) or die ( "CORE VARIABLE IS NOT DEFINED." );
	Import::AppLib("word");
	class ArticleController extends Controller {
		public function view(){
			$id = Basic::getVar("id");
			$article = $this->loadModel("Article");
			if ( $id ){
				$this->set("selectedMenu","ART");
				$this->setLanguage( "English" );
				$this->set("title","SMECA - Article View");
				$articleinfo = $article->find( $id );
				$this->set("article",$articleinfo[0]);
				$this->renderDefault("view", "article" );
			}else{
				$this->index();
			}
		}
		public function lastarticle(){
			$page = Basic::getVar("page");
			$article = $this->loadModel("Article");
			$_SESSION['nav']['page-latest'] = $page;
			$articles = $article->getLatestArticle($_SESSION["lang"] , 5 , $page );
			$this->set("lastArticles",$articles);
			$this->renderDefault("lastarticles","article");
		}
		public function index(){
			$start = Basic::getVar("start");
			$perpage = Basic::getVar("perpage");
			$search = Basic::getVar("search");
			$start = is_numeric($start)&&$start>-1?$start:0;
			$perpage = is_numeric($perpage)&&$perpage>-1?$perpage:15;
			$searchColumns = Basic::getVar("search_column")?Basic::getVar("search_column"):false;
			$sortColumn = Basic::getVar("sort_column")?Basic::getVar("sort_column"):"id";
			$sortCriteria = Basic::getVar("sort_criteria")?Basic::getVar("sort_criteria"):false;
			$article = $this->loadModel("Article");
			$articleRecords = $article->display($start,$perpage,$search,$searchColumns,$sortColumn,$sortCriteria) ;
			$totalRecords = $article->getTotalRecords();
			if ( $start < $totalRecords ){
				$this->set("totalRows",$totalRecords);
			}elseif ( $start >= $totalRecords ) {
				$start = $start-15;
				$articleRecords = $article->display($start,$perpage,$search,$searchColumns,$sortColumn,$sortCriteria) ;
				$this->set("totalRows",$totalRecords);
			}
			$this->set("currentPage",$start);
			$this->set("perpage",$perpage);
			$this->set("search",$search);
			$this->set("searchColumns",$searchColumns);
			$this->set("sortColumn",$sortColumn);
			$this->set("sortCriteria",$sortCriteria);
			$this->set("search",$search);
			$this->set("articles",$articleRecords);
			$this->set("selectedMenu","ART");
			
			$this->set( "title" , "SMECA - Article List" );
			$this->setLanguage( "English" );
			$this->renderDefault("display","article");
		}	
		public function add(){
			$resource = $this->loadModel("resource");
			$article = $this->loadModel("Article");
			$articlesPublished = $resource->getPublished();
			$resources = array(); 
			foreach( $articlesPublished As $key => $articlePublished ){
				$resources[$articlePublished->id] = $articlePublished->name ;
			}
			$this->set("menus", $article->getMenu());
			$this->set('resources',$resources);
			$this->set("selectedMenu","ART");
			$this->set( "title" , "SMECA - Article New" );
			$this->setLanguage( "English" );
			$this->renderDefault("add","article" );
		}
		public function edit(){
			if(isset($_SESSION['edit-thumbnail'])) unset($_SESSION['edit-thumbnail']);
			$id = Basic::getVar("id");
			$resource = $this->loadModel("resource");
			$articlesPublished = $resource->getPublished();
			$resources = array();
			foreach( $articlesPublished As $key => $articlePublished ){
				$resources[$articlePublished->id] = $articlePublished->name ;
			}
			$this->set('resources',$resources);
			$article = $this->loadModel("Article");
			$category = $article->getCategory();
			$this->set("menus", $article->getMenu());
			$this->set("category",$category);
			$this->set("selectedMenu","ART");
			$this->set( "title" , "SMECA - Article Edit" );
			$this->setLanguage( "English" );
			if ( $id ){
				$articleinfo = $article->find( $id );
				$this->set("article",$articleinfo[0]);
				$this->renderDefault("edit", "article" );
			}else{
				$this->index();
			}
		}
		function imagethumbnail(){
			$id = @$_GET['id'];
			if(isset($_GET['op'])){
				$_SESSION['op'] = $_GET['op'];
			}
			$user = $this->loadModel("Article");
			if(@$_GET['op'] == "remove"){
				$user -> removeThumbnail($_SESSION['art-id'],1);
				$this->redirect( array("com"=>"article","action"=>"edit&id=" . $id));
				exit();
			}
			if(!empty($_FILES)){
				/*
				 * Image Uploader File
				* ===================
				*
				* This file only move the uploaded images
				* to the destination folder
				*/
				
				// Detect the file params according to need
				$filename = $_FILES["myfile"]["name"];
				$filesize = $_FILES["myfile"]["size"];
				$tmp_name = $_FILES["myfile"]["tmp_name"];
				
				// Valid extensions for Upload
				$validExtensions = array('.jpeg', '.jpg', '.gif', '.png');
				
				// Valid size in KB
				$max_size = 2048;
				
				// Detect file extension
				$extension = strtolower(strrchr($filename, "."));
				$newname = "az" . date("Ymdhis") . $extension;
				// Convert filesize in KB
				$getFileSize = round($filesize / 1024, 1);
				
				// Location to store the file
				//$path = str_replace('\/\\', '/', dirname(__FILE__)) . "/image/";
				$path = IMG_FOLDER . 'articles/tmp-thumbnails/';
				list($w, $h) = getimagesize($_FILES["myfile"]["tmp_name"]);
				if($w >= 125 && $w <= 664 && $h >= 90){
					if( in_array($extension, $validExtensions) ){				
						if( $getFileSize < $max_size ){
							
							if(is_dir($path)){				
								move_uploaded_file($tmp_name, "$path/$newname");
								$_SESSION['tmp-thumbnail-path'] = $path . DS . $newname;
								if($id != "") $_SESSION['art-id'] = $id;																
								if(@$_SESSION['op'] == ""){									
									$user -> updateField($_SESSION['art-id'], $newname);
									unset($_SESSION['edit-thumbnail']);								
								}else{
									$user -> updateField($_SESSION['art-id'], $newname,1);
									$_SESSION['edit-thumbnail'] = "edit&id=" . $id;
									unset($_SESSION['op']);
								}
								$this->redirect( array("com"=>"article","action"=>"createthumbnail"));
							}
						}else{
							Die("Sorry, image size can not larger then 2M.");
						}
					}else{
						die('Sorry, your image extension is not allow.');
					}
				}else{
						die("Sorry, image dimensions should be:<br> - 125px <= <b>width</b> <= 664px <br> - 90px <= <b>height</b> up to ");
					}
			}else{
				$this->set("selectedMenu","ART");
				$this->set( "title" , "SMECA - Upload Image" );
				$this->setLanguage( "English" );
				$this->renderDefault("imagethumbnail","article" );
			}
		}
		function createthumbnail(){
			$this->set("selectedMenu","ART");
			$this->set( "title" , "SMECA - Create Thumbnail" );
			$this->setLanguage( "English" );
			$this->set('img', $_SESSION['tmp-thumbnail-path']);
			$this->renderDefault("createthumbnail","article" );
		}
		function cropimage(){
			//$targ_w = $targ_h = 150;
			$b_w = 280;
			$b_h = 202;
			$jpeg_quality = 100;
			
			$arr_img_info = array(
					'lastest_thumb' => array(
							'path' => IMG_FOLDER . 'articles/latest-thumbnails/',
							'width' => 125,
							'height' => 90
							),
					/*'top_thumb' => array(
							'path' => IMG_FOLDER . 'articles/top-thumbnails/',
							'width' => 125,
							'height' => 96
							),*/
					'top_thumb_active' => array(
							'path' => IMG_FOLDER . 'articles/top-thumbnail-actives/',
							'width' => 280,
							'height' => 202
							)
					);
			
			if(!isset($_POST['x']) || !is_numeric($_POST['x'])) {
				die('Please select a crop area.');
			}
			$src = $_POST['image'];
			$filename = basename($src);			
			$img_r = imagecreatefromjpeg($src);
			foreach($arr_img_info as $key => $val){
				$targ_w = $val['width'];
				$targ_h = $val['height'];
				$targ_p = $val['path'] . $filename;
				
				$start_x = $_POST['x'];
				$start_y = $_POST['y'];
				
				$w_selected = $_POST['w'];
				$h_selected = $_POST['h'];
				
				/*if($key == "top_thumb"){
					$w = ($w_selected * $targ_w)/$b_w;
					$w_selected = $w;
					
					$n_x = ($w*$start_x)/$b_w;
					$start_x = ( $start_x - (($start_x - $n_x)/4) );
					
				}*/
				/*if($key == "top_thumb_active"){
					$w = ($w_selected * $targ_w)/$b_w;
					$h = ($h_selected * $targ_h)/$b_h;
					$w_selected = $w;
					$h_selected = $h;
					
					$n_x = ($w*$start_x)/$b_w;
					$start_x = ( $start_x + (($start_x - $n_x)/4) );
					
					$n_h = ($h*$start_h)/$b_h;
					$start_y = ( $start_h + (($start_h - $n_h)/4) );
				}*/
				
				$dst_r = ImageCreateTrueColor($targ_w, $targ_h);
				
				imagecopyresampled($dst_r,$img_r,0,0,$start_x,$start_y,
				$targ_w,$targ_h,$w_selected,$h_selected);
				
				header('Content-type: image/jpeg');
				//imagejpeg($dst_r,null,$jpeg_quality); // NULL will output the image directly
				imagejpeg($dst_r,$targ_p,$jpeg_quality); // NULL will output the image directly
			}
			@unlink($_SESSION['tmp-thumbnail-path']);
			unset($_SESSION['tmp-thumbnail-path']);
			unset($_SESSION['tmp_name']);
			unset($_SESSION['top_thumb']);
			unset($_SESSION['top_thumb_active']);
			unset($_SESSION['lastest_thumb']);
			if(isset($_SESSION['edit-thumbnail'])){
				$path = $_SESSION['edit-thumbnail'];
				unset($_SESSION['edit-thumbnail']);
				$this->redirect( array("com"=>"article","action"=>$path));
				exit();
			}
			$this->redirect( array("com"=>"article","action"=>"index"));
			exit;
		}		
		public function skipthumbnail(){
			$article = $this->loadModel("Article");
			$article->skipThumbail($_SESSION['art-id']);
			$this->redirect( array("com"=>"article","action"=>"index"));
		}
		public function addprocess(){			
			
			$article = $this->loadModel("Article");
			$user = SESSION::get("user");
			$_POST['data']['az_articles']['created_by'] = $user->id;
			$_POST['data']['az_articles']['modified_by'] = $user->id;
			$id = $article->add($_POST['data']);	
			if( $id ){				
				$this->set("info","Article is added successfully.");
				//$id = $article->add( $title , $resource , $published , $content , $user->id );
			}
			else{
				$this->set("info","Failed to add article.");
			}
			if($_POST['data']['az_articles']['is_thumbnail'] == "1"){
				$_SESSION['art-id'] = $id;
				$this->redirect( array("com"=>"article","action"=>"imagethumbnail", "id" => $id));
			}else{
				$this->redirect( array("com"=>"article","action"=>"index"));
			}
		}
		public function editprocess(){
			$article = $this->loadModel("Article");
			$user = SESSION::get("user");
			$_POST['data']['az_articles']['modified_by'] = $user->id;
			if( $article->edit($_POST['data']) ){
				$this->set("info","Article information is updated succeffully.");
			}else{
				$this->set("info","Failed to update article information.");
			}
			$this->redirect( array("com"=>"article","action"=>"index"));
		}
		public function delete(){
			$id = Basic::getVar("id");
			$user = $this->loadModel("Article");
			if ( $id ){
				$this->set("info","Article(s) delete successfully.");
				$user->delete( $id );
			}else{
				$this->set("info","Failed to delete article(s) successfully.");
			}
			$this->redirect( array("com"=>"article","action"=>"index"));
		}
		public function getCategory(){
			$menu_id = Basic::getVar('menu_id');
			$category = $this->loadModel( "Article" );
			$categories = $category->getCategory($menu_id);
			$options = "<option value=''>-- Please Select Category --</option>";
			if(isset($categories)){
				foreach($categories as $cat){
					$options .= '<option value="' . $cat->id . '">' . $cat->title . '</option>';
				}
			}
			echo $options;
		}
		public function search(){
			$str = Basic::getVar("str");
			if ( $str ){
				
			}
		}
		
	}
?>